package com.doupi.partner.manager.authenticator.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.mgt.AuthorizingSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 权限相关工具类
 * 
 * @author Alvin Wang
 * @version 1.0.0 @ 2017-04-16
 */
public class PermissionUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(PermissionUtils.class);
	private static final String ERROR_MESSAGE_TIP = "权限处理异常";

	public static boolean checkWholePermissionString(String permission) {
		try {
			Subject subject = SecurityUtils.getSubject();
			if (null != subject && !subject.getPrincipals().isEmpty()) {
				SecurityManager securityManager = SecurityUtils.getSecurityManager();
				if (null != securityManager && securityManager instanceof AuthorizingSecurityManager) {
					AuthorizingSecurityManager authorizingSecurityManager = (AuthorizingSecurityManager) securityManager;
					Authorizer authorizer = authorizingSecurityManager.getAuthorizer();
					if (null != authorizer && authorizer instanceof ModularRealmAuthorizer) {
						ModularRealmAuthorizer modularRealmAuthorizer = (ModularRealmAuthorizer) authorizer;
						Collection<Realm> realms = modularRealmAuthorizer.getRealms();
						Class<AuthorizingRealm> clazz = AuthorizingRealm.class;
						Method method = clazz.getDeclaredMethod("getAuthorizationInfo", PrincipalCollection.class);
						method.setAccessible(true);
						for (Realm realm : realms) {
							if (null != realm && realm instanceof AuthorizingRealm) {
								AuthorizationInfo authorizationInfo = (AuthorizationInfo) method.invoke(realm, subject.getPrincipals());
								Collection<String> stringPermissions = authorizationInfo.getStringPermissions();
								if (stringPermissions.contains(permission)) {
									return true;
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error(ERROR_MESSAGE_TIP, e);
		}
		return false;
	}

}
